<?php

// Namespace

namespace Loop;


/**
 * CFileHelper is a helper that contains various functions to help developers deal with files
 *
 * @package		Loop
 * @category	Helper
 */

class CFileHelper
{
	/**
	 * This method create a folder/directory with path in parameter
	 *
	 * @param	string	$pathToFile	The path of the file
	 */

	public function createFile($pathToFile)
	{
		$filename = basename($pathToFile);
		$path = dirname($pathToFile);

		if
		(
			(file_exists($path) == true) &&
			(file_exists($filename) == false)
		)
		{
			fopen($pathToFile, 'w');
		}	
	}


	/**
	 * Creates a path made of directories
	 * 
	 * @param 	array 		$pathFragments		The array of path fragments
	 * @param 	boolean		$createPath			Is the path need to be created 	
	 * @param 	boolean		$isSmart 			Is environment or universe need to added into $pathFragments 
	 *
 	 * @return  string 		The path 	
	 */
	
	public function createPath($pathFragments, $createPath = false, $isSmart = true)
	{
		// Path fragments have to be an array and contain at least one fragment

		if
		(
			(is_array($pathFragments) === true) &&
			(empty($pathFragments) === true)
		)
		{
			e(EXCEPTION_FILE_PATH_EMPTY);
		}


		// If the path is PATH_TEMPORARY or Data, we need to append a few directories

		if
		(
			(isset($pathFragments[0]) === true) &&
			($pathFragments[0] === PATH_TEMPORARY)
		)
		{
			// Add the session ID

			if
			(
				($isSmart === true) &&
				(count($pathFragments) > 1)
			)
			{
				array_push($pathFragments, session_id());
			}


			// For temporary files, always create the path

			$createPath = true;
		}
		else if
		(
			(isset($pathFragments[1]) === true) &&
			($pathFragments[1] === 'Data')
		)
		{
			// Add the environment

			array_splice
			(
				$pathFragments,
				2,
				0,
				env()
			);


			// Add the universe

			if ($isSmart === true)
			{
				array_splice
				(
					$pathFragments,
					2,
					0,
					pref('[Loop]/application/universe')
				);
			}
		}

		
		// Now create the final path

		$path = null;
		
		foreach ($pathFragments as $pathFragment)
		{
			// Ignore directories with no name
			
			if (empty($pathFragment) === true)
			{
				continue;
			}
			
			
			// Add the path fragment to the final path

			$path .= $pathFragment;

			if ($path[strlen($path) - 1] != '/')
			{
				$path .= '/';
			}
			
			// Create the path if it doesn't exist yet
			
			if
			(
				($createPath === true) &&
				(file_exists($path) === false)
			)
			{
				mkdir($path);
				chmod($path, 0777);
			}
		}


		return $path;
	}


	/**
	 * Completely removes a directory and files / sub-directories in it
	 *
	 * @param	string	$pathToDirectory	The path to the directory to be deleted
	 */
	
	public function deleteDirectory($pathToDirectory)
	{
		// Exit if directory does not exist
		
		if (file_exists($pathToDirectory) == false)
		{
			return;
		}
		
		
		$filenames = scandir($pathToDirectory);
		
		foreach ($filenames as $filename)
		{
			$pathToFile = $pathToDirectory . $filename;
			
			if
			(
				($filename == '.') ||
				($filename == '..')
			)
			{
				continue;
			}
			else if (is_dir($pathToFile) == true)
			{
				self::deleteDirectory($pathToFile . '/');
			}
			else
			{
				unlink($pathToFile);
			}
		}
		
		rmdir($pathToDirectory);
	}
	
	
	/**
	 * Scans a directory and lists all files
	 *
	 * @param 	$path 		The path of directory to scan
	 * @param 	$pattern 	The pattern
	 * 
	 * @return 	The array containing the matched files/directory 
	 */
	
	public function listFiles($path, $pattern = '*')
	{
		// Make sure the path ends with a slash
		
		if (substr($path, -1) != '/')
		{
			$path .= '/';
		}
		
		
		// Find files matching the pattern
		
		$files = glob($path . $pattern);
		
		
		return $files;
	}


	/**
	 * Creates a text file into "/Temporary/Deposit/{Key}/", and write the data (encoding elements into json) into it
	 * 
	 * @param 	mixed 	$data 	The elements to store into the text file
	 * 
	 * @return 	string 	The generated key 	
	 */

	public function depositData($data)
	{
		// Set a unique key for this data deposit

		$dataKey = app()->getStringHelper()->generateUuid();

		
		// Build its path

		$pathToData = path
		(
			array
			(
				PATH_TEMPORARY,
				'Deposit'
			),
			true
		);

		$pathToData .= $dataKey . '.txt';


		// Store the JSON version of data

		file_put_contents($pathToData, json_encode($data));


		return $dataKey;
	}


	/**
	 * Read a text file into "/Temporary/Deposit/{Key}/", delete the file and return the contents
	 * 
	 * @param 	string 	$dataKey 	The file name to read
	 * 
	 * @return 	mixed 	The contents json decoded
	 */

	public function pickUpData($dataKey)
	{
		// Build the path to the data deposit

		$pathToData = path
		(
			array
			(
				PATH_TEMPORARY,
				'Deposit'
			)
		);

		$pathToData .= $dataKey . '.txt';


		// It has to exist

		if (file_exists($pathToData) === false)
		{
			e
			(
				EXCEPTION_FILE_NOT_FOUND,
				array
				(
					'pathToFile' => $pathToData
				)
			);
		}


		// Get data and decode it from JSON

		$data = json_decode(file_get_contents($pathToData), true);


		// Remove the deposit

		unlink($pathToData);


		return $data;
	}
}

?>
